import {
  _decorator,
  Collider,
  Component,
  input,
  Input,
  KeyCode,
  Node,
  RigidBody,
  Vec2,
  Vec3,
  type EventKeyboard,
  type ICollisionEvent,
  type ITriggerEvent,
} from 'cc'
const { ccclass, property } = _decorator

@ccclass('player')
export class player extends Component {
  @property
  public moveForce = 100

  private moveDir: Vec2 = Vec2.ZERO
  private rgd: RigidBody = null
  private collider: Collider = null

  protected onLoad(): void {
    input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this)
    input.on(Input.EventType.KEY_UP, this.OnKeyUp, this)
  }

  start() {
    this.rgd = this.getComponent(RigidBody)

    this.collider = this.node.getComponent(Collider)
    // this.collider.on('onCollisionEnter', this.onCollisionEnter, this)
    this.collider.on('onTriggerEnter', this.onTriggerEnter, this)
  }

  update(deltaTime: number) {
    this.rgd.applyForce(new Vec3(this.moveDir.x, 0, this.moveDir.y).multiplyScalar(this.moveForce))
  }

  protected onDestroy(): void {
    // this.collider.off('onCollisionEnter', this.onCollisionEnter, this)
  }

  onKeyDown(e: EventKeyboard) {
    switch (e.keyCode) {
      case KeyCode.KEY_A:
        this.moveDir = new Vec2(-1, this.moveDir.y)
        break
      case KeyCode.KEY_D:
        this.moveDir = new Vec2(1, this.moveDir.y)
        break
      case KeyCode.KEY_W:
        this.moveDir = new Vec2(this.moveDir.x, -1)
        break
      case KeyCode.KEY_S:
        this.moveDir = new Vec2(this.moveDir.x, 1)
        break

      default:
        break
    }
  }

  OnKeyUp(e: EventKeyboard) {
    switch (e.keyCode) {
      case KeyCode.KEY_A:
        this.moveDir = new Vec2(0, this.moveDir.y)
        break
      case KeyCode.KEY_D:
        this.moveDir = new Vec2(0, this.moveDir.y)
        break
      case KeyCode.KEY_W:
        this.moveDir = new Vec2(this.moveDir.x, 0)
        break
      case KeyCode.KEY_S:
        this.moveDir = new Vec2(this.moveDir.x, 0)
        break

      default:
        break
    }
  }

  //   onCollisionEnter(e: ICollisionEvent) {
  //     const food = e.otherCollider.getComponent('FoodRotate')
  //     if (food) {
  //       console.log(`currentFood -->`, food)
  //       food.node.destroy()
  //     }
  //   }

  onTriggerEnter(e: ITriggerEvent) {
    const food = e.otherCollider.getComponent('FoodRotate')
    if (food) {
      console.log(`currentFood -->`, food)
      food.node.destroy()
    }
  }
}
console.log(` -->`)
